package com.ytkj.digitalConstruction.controller.dept;

import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ytkj.digitalConstruction.ReturnCode;
import com.ytkj.digitalConstruction.entity.user.User;
import com.ytkj.digitalConstruction.httpbean.PageResult;
import com.ytkj.digitalConstruction.httpbean.dept.req.PageDept;
import com.ytkj.digitalConstruction.httpbean.dept.req.ReqDept;
import com.ytkj.digitalConstruction.httpbean.dept.res.ResAdd;
import com.ytkj.digitalConstruction.httpbean.user.resbean.UserRoleBean;
import com.ytkj.digitalConstruction.service.dept.DeptService;

/**
 * 部门请求入口
 * 
 * @author Pete
 * @Date 2017年12月7日
 */
@RestController
@RequestMapping("/depts")
public class DeptController {
	private final static Logger log = LoggerFactory.getLogger(DeptController.class);

	@Autowired
	private DeptService deptService;
	
	/**
	 * 添加部门
	 * 
	 * @param req
	 * @return
	 */
	@PostMapping("/add")
	public ReturnCode add(@RequestBody @Valid ReqDept req, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		//判断所选的父部门下是否有同名的部门
		if(deptService.isHaveSameName(req.dept().getParentId(),req.getDeptName())) {
			log.error("在所选部门下有同名部门：" + req.toString());
			return new ReturnCode.Builder().Success(false).Msg("在所选部门下有同名部门！").Object(req).build();
		}
	
		String resMsg = deptService.addDept(req);
		if (!StringUtils.isEmpty(resMsg)) {
			log.error("添加部门失败：" + req.toString());
			return new ReturnCode.Builder().Success(false).Msg(resMsg).Object(req).build();
		}
		log.info("添加部门成功：" + req.toString());
		ResAdd res = null;
		String resStr = JSONObject.toJSONString(req);
		res = JSONObject.parseObject(resStr,ResAdd.class);
		res.setParentIds(deptService.findAncestors(res.getParentId()));
		return new ReturnCode.Builder().Success(true).Msg("添加部门成功！").Object(res).build();

	}

	/**
	 * 删除部门
	 * 
	 * @param deptId
	 * @return
	 */
	@GetMapping("/delete/{deptId}")
	public ReturnCode delete(@PathVariable("deptId") Integer deptId) {
		// 判断参数是否为空		
		if (deptId == null) {
			log.error("传入参数不能为空");
			return new ReturnCode.Builder().Success(false).Msg("传入参数不能为空").build();
		}
		if(deptId < 1) {
			log.error("传入参数有误");
			return new ReturnCode.Builder().Success(false).Msg("传入参数只能为正数").build();
		}
		//判断部门下是否有子集
		if(deptService.isHaveSubSet(deptId)){
			return new ReturnCode.Builder().Success(false).Msg("该部门下有子部门，请先删除子部门！").build();
		}
		//判断是否有在职人员
		if(deptService.isHaveUser(deptId)){
			return new ReturnCode.Builder().Success(false).Msg("该部门下人员，请删除人员！").build();
		}
		boolean success = deptService.deleteDept(deptId);
		if (success == false) {
			log.error("删除部门失败");
			return new ReturnCode.Builder().Success(false).Msg("删除部门失败").build();
		}
		log.info("删除成功");
		return new ReturnCode.Builder().Success(true).Msg("删除成功").build();
	}

	/**
	 * 修改部门
	 * 
	 * @param req
	 * @return
	 */
	@PostMapping("/update")
	public ReturnCode update(@RequestBody @Valid ReqDept req, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}

		if(!deptService.checkParentId(req)) {
			log.error("父级id校验失败！");
			return new ReturnCode.Builder().Success(false).Msg("父级id有误！").build();
		}
		// 修改部门
		String resMsg = deptService.updateDept(req);
		if (!StringUtils.isEmpty(resMsg)) {
			log.error("修改失败");
			return new ReturnCode.Builder().Success(false).Msg(resMsg).build();
		}
		log.error("修改成功");
		return new ReturnCode.Builder().Success(true).Msg("修改成功").build();

	}

	/**
	 * 分页获取部门所有用户
	 * 
	 * @param pageDept
	 * @return
	 */
	@PostMapping("/users/")
	public ReturnCode getUsers(@RequestBody @Valid PageDept pageDept,BindingResult result) {
		// 判断参数是否合法
		if (result.hasErrors()) {
			String msg = result.getFieldError().getDefaultMessage();
			log.error(msg);
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		//获取部门所有用户
		PageResult<UserRoleBean> pageResult = deptService.getUsers(pageDept);
		
		/*//获取当前用户
		String webToken = request.getHeader("x-access-token");
		User currentUser = userService.getUserByWebToken(webToken);
		if(currentUser == null){			
			return new ReturnCode.Builder().Success(false).Msg("获取当心用户信息失败!").build();
		}
		//若当前用户不是高管，则把高管的电话号码隐藏
		if(currentUser.getIsManager() == false) {
			userService.hiddenManagerMobile(pageResult.getItems());	
		}*/
		
		log.info("获取部门所有用户成功");
		return new ReturnCode.Builder().Success(true).Msg("获取部门所有用户成功").Object(pageResult).build();
	}
	
	
	
	/**
	 * 获取部门所有用户
	 * 
	 * @param deptId
	 * @return
	 */
	@GetMapping("/users/{deptId}")
	public ReturnCode users(@PathVariable Integer deptId) {
		if(deptId < 0) {
			log.error("deptId 为负数！");
			return new ReturnCode.Builder().Success(false).Msg("参数有误！").build();
		}
		List<UserRoleBean> userRoleBeanList = deptService.getUsers(deptId);
		
		/*//获取当前用户
		String webToken = request.getHeader("x-access-token");
		User currentUser = userService.getUserByWebToken(webToken);
		if(currentUser == null){			
			return new ReturnCode.Builder().Success(false).Msg("获取当心用户信息失败!").build();
		}
		//若当前用户不是高管，则把高管的电话号码隐藏
		if(currentUser.getIsManager() == false) {
			userService.hiddenManagerMobile(userRoleBeanList);	
		}*/
		
		log.info("获取部门所有用户成功");
		return new ReturnCode.Builder().Success(true).Msg("获取部门所有用户成功").Object(userRoleBeanList).build();
	}

	@GetMapping("/getAll")
	public ReturnCode getAll() {
		log.info("获取所有部门人员成功");
		return new ReturnCode.Builder().Success(true).Object(deptService.getAll()).build();
	}
	
	/**
	 * 获取父节点及传入节点本身的id list
	 * @param deptId
	 * @return
	 */
	@GetMapping("/ancestors/{deptId}")
	public ReturnCode findAncestors(@PathVariable("deptId") Integer deptId) {
		if(deptId < 0) {
			return new ReturnCode.Builder().Success(false).Msg("参数不能为负数！").build();
		}
		List<Integer> deptIds = deptService.findAncestors(deptId);
		if(deptIds.isEmpty()) {
			return new ReturnCode.Builder().Success(true).Msg("查询为空！").Object(deptIds).build();
		}
		return new ReturnCode.Builder().Success(true).Msg("查询成功！").Object(deptIds).build();
	}
	
	/**
	 * 查询指定项目对应的项目组下的所有人员
	 * 
	 * @param proId
	 * @return
	 */
	@GetMapping("/virDept/user/{proId}")
	public ReturnCode findVirDeptUser(@PathVariable Integer proId) {
		if(proId < 0) {
			return new ReturnCode.Builder().Success(false).Msg("参数有误！").Object(proId).build();
		}
		List<User> users = deptService.findVirDeptUser(proId);
		return new ReturnCode.Builder().Success(true).Msg("获取成功！").Object(users).build();
	}
	
	
	/**
	 * 获取指定项目部的角色为施工单位人员
	 * 
	 * @param proId
	 * @return
	 */
	@GetMapping("/virDept/exeUser/{proId}")
	public ReturnCode findVirDeptExeUser(@PathVariable Integer proId) {
		if(proId < 0) {
			return new ReturnCode.Builder().Success(false).Msg("参数有误！").Object(proId).build();
		}
		List<User> users = deptService.findVirDeptExeUser(proId);
		
		return new ReturnCode.Builder().Success(true).Msg("获取成功！").Object(users).build();
	}

}
